<template>
  <div class="app-container">
    <div class="block">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="listQuery.account" placeholder="请输入帐号"></el-input>
        </el-col>
        <el-col :span="6">
          <el-input v-model="listQuery.name" placeholder="请输入姓名"></el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="success" icon="el-icon-search" @click.native="search">{{
            $t('button.search')
          }}</el-button>
          <el-button type="primary" icon="el-icon-refresh" @click.native="reset">{{
            $t('button.reset')
          }}</el-button>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :span="24">
          <el-button
            type="success"
            icon="el-icon-plus"
            @click.native="add"
            v-permission="['/mgr/add']"
          >
            {{ $t('button.add') }}
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click.native="edit"
            v-permission="['/mgr/edit']"
          >
            {{ $t('button.edit') }}
          </el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click.native="remove"
            v-permission="['/mgr/delete']"
          >
            {{ $t('button.delete') }}
          </el-button>
          <el-button type="info" icon="el-icon-role" @click.native="openRole">角色分配</el-button>
        </el-col>
      </el-row>
    </div>

    <el-table
      :data="list"
      v-loading="listLoading"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @current-change="handleCurrentChange"
    >
      <el-table-column label="账号">
        <template slot-scope="scope">
          {{ scope.row.account }}
        </template>
      </el-table-column>
      <el-table-column label="姓名">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="性别">
        <template slot-scope="scope">
          {{ scope.row.sexName }}
        </template>
      </el-table-column>
      <el-table-column label="角色">
        <template slot-scope="scope">
          {{ scope.row.roleName }}
        </template>
      </el-table-column>
      <el-table-column label="部门">
        <template slot-scope="scope">
          {{ scope.row.deptName }}
        </template>
      </el-table-column>
      <el-table-column label="邮箱">
        <template slot-scope="scope">
          {{ scope.row.email }}
        </template>
      </el-table-column>
      <el-table-column label="电话">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.createtime }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          {{ scope.row.statusName }}
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100, 500]"
      :page-size="listQuery.limit"
      :total="total"
      @size-change="changeSize"
      @current-change="fetchPage"
      @prev-click="fetchPrev"
      @next-click="fetchNext"
    >
    </el-pagination>

    <el-dialog :title="formTitle" :visible.sync="formVisible" width="70%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="账户" prop="account">
              <el-input v-model="form.account" minlength="1"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" minlength="1"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="性别">
              <el-radio-group v-model="form.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="isAdd">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="isAdd">
            <el-form-item label="确认密码" prop="rePassword">
              <el-input v-model="form.rePassword" type="password"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门">
              <el-input
                placeholder="请选择所属部门"
                v-model="form.deptName"
                readonly="readonly"
                @click.native="deptTree.show = !deptTree.show"
              >
              </el-input>
              <el-tree
                v-if="deptTree.show"
                empty-text="暂无数据"
                :expand-on-click-node="false"
                :data="deptTree.data"
                :props="deptTree.defaultProps"
                @node-click="handleNodeClick"
                class="input-tree"
              >
              </el-tree>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="status">
              <el-switch v-model="form.status"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="form.birthday"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="saveUser">{{ $t('button.submit') }}</el-button>
          <el-button @click.native="formVisible = false">{{ $t('button.cancel') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="角色分配" :visible.sync="roleDialog.visible" width="25%">
      <el-form>
        <el-row>
          <el-col :span="12">
            <el-tree
              :data="roleDialog.roles"
              ref="roleTree"
              show-checkbox
              node-key="id"
              :default-checked-keys="roleDialog.checkedRoleKeys"
              :props="roleDialog.defaultProps"
            >
            </el-tree>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="setRole">{{ $t('button.submit') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getList, saveUser, remove, setRole } from '@/api/system/user';
import { list as deptList } from '@/api/system/dept';
import { parseTime } from '@/utils/index';
import { roleTreeListByIdUser } from '@/api/system/role';
// 权限判断指令
import permission from '@/directive/permission/index.js';

export default {
  directives: { permission },
  data() {
    return {
      roleDialog: {
        visible: false,
        roles: [],
        roleTree: [],
        checkedRoleKeys: [],
        defaultProps: {
          id: 'id',
          label: 'name',
          children: 'children',
        },
      },
      formVisible: false,
      formTitle: '添加用户',
      deptTree: {
        show: false,
        data: [],
        defaultProps: {
          id: 'id',
          label: 'simplename',
          children: 'children',
        },
      },
      isAdd: true,
      form: {
        id: '',
        account: '',
        name: '',
        birthday: '',
        sex: 1,
        email: '',
        password: '',
        rePassword: '',
        dept: '',
        status: true,
        deptid: 1,
        deptName: '',
      },
      rules: {
        account: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
        ],
        email: [{ required: true, message: '请输入email', trigger: 'blur' }],
      },
      listQuery: {
        page: 1,
        limit: 20,
        account: undefined,
        name: undefined,
      },
      total: 0,
      list: null,
      listLoading: true,
      selRow: {},
    };
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger',
      };
      return statusMap[status];
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      deptList().then((response) => {
        this.deptTree.data = response.data;
      });
      this.fetchData();
    },
    fetchData() {
      this.listLoading = true;
      getList(this.listQuery).then((response) => {
        this.list = response.data.records;
        this.listLoading = false;
        this.total = response.data.total;
      });
    },
    search() {
      this.fetchData();
    },
    reset() {
      this.listQuery.account = '';
      this.listQuery.name = '';
      this.fetchData();
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleClose() {},
    fetchNext() {
      this.listQuery.page = this.listQuery.page + 1;
      this.fetchData();
    },
    fetchPrev() {
      this.listQuery.page = this.listQuery.page - 1;
      this.fetchData();
    },
    fetchPage(page) {
      this.listQuery.page = page;
      this.fetchData();
    },
    changeSize(limit) {
      this.listQuery.limit = limit;
      this.fetchData();
    },
    handleCurrentChange(currentRow) {
      this.selRow = currentRow;
    },
    resetForm() {
      this.form = {
        id: '',
        account: '',
        name: '',
        birthday: '',
        sex: 1,
        email: '',
        password: '',
        rePassword: '',
        dept: '',
        status: true,
        deptid: 1,
      };
    },
    add() {
      this.resetForm();
      this.formTitle = '添加用户';
      this.formVisible = true;
      this.isAdd = true;
    },
    validPasswd() {
      if (!this.isAdd) {
        return true;
      }
      if (this.form.password !== this.form.rePassword) {
        return false;
      }
      if (this.form.password === '' || this.form.rePassword === '') {
        return false;
      }
      return true;
    },
    saveUser() {
      var self = this;
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.validPasswd()) {
            var form = self.form;
            if (form.status === true) {
              //启用
              form.status = 1;
            } else {
              //冻结
              form.status = 2;
            }
            form.birthday = parseTime(form.birthday, '{y}-{m}-{d}');
            form.createtime = parseTime(form.createtime);
            saveUser(form).then(() => {
              this.$message({
                message: '提交成功',
                type: 'success',
              });
              this.fetchData();
              this.formVisible = false;
            });
          } else {
            this.$message({
              message: '提交失败',
              type: 'error',
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    checkSel() {
      if (this.selRow && this.selRow.id) {
        return true;
      }
      this.$message({
        message: '请选中操作项',
        type: 'warning',
      });
      return false;
    },
    edit() {
      if (this.checkSel()) {
        this.isAdd = false;

        this.form = this.selRow;
        this.form.status = this.selRow.statusName === '启用';
        this.form.password = '';
        this.formTitle = '修改用户';
        this.formVisible = true;
      }
    },
    remove() {
      if (this.checkSel()) {
        var id = this.selRow.id;

        this.$confirm('确定删除该记录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            remove(id)
              .then(() => {
                this.$message({
                  message: '删除成功',
                  type: 'success',
                });
                this.fetchData();
              })
              .catch((err) => {
                this.$notify.error({
                  title: '错误',
                  message: err,
                });
              });
          })
          .catch(() => {});
      }
    },
    handleNodeClick(data) {
      this.form.deptid = data.id;
      this.form.deptName = data.simplename;
      this.deptTree.show = false;
    },

    openRole() {
      if (this.checkSel()) {
        roleTreeListByIdUser(this.selRow.id).then((response) => {
          this.roleDialog.roles = response.data.treeData;
          this.roleDialog.checkedRoleKeys = response.data.checkedIds;
          this.roleDialog.visible = true;
        });
      }
    },
    setRole() {
      var checkedRoleKeys = this.$refs.roleTree.getCheckedKeys();
      var roleIds = '';
      for (var index in checkedRoleKeys) {
        roleIds += checkedRoleKeys[index] + ',';
      }
      var data = {
        userId: this.selRow.id,
        roleIds: roleIds,
      };
      setRole(data).then(() => {
        this.roleDialog.visible = false;
        this.fetchData();
        this.$message({
          message: '提交成功',
          type: 'success',
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import '~@/styles/common.scss';
</style>
